package com.quan.weixin.web.controller;

import java.util.ArrayList;
import java.util.List;

import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quan.common.bean.PageBean;
import com.quan.common.bean.R;
import com.quan.common.core.MyBaseController;
import com.quan.common.utils.RandomUitl;
import com.quan.weixin.commons.tree.WxMenuTreeGridUtil;
import com.quan.weixin.commons.tree.WxMenuTreeNode;
import com.quan.weixin.entity.WeixinMenu;
import com.quan.weixin.service.WeixinMenuService;

/**
 * <p>
 * 微信菜单 前端控制器
 * </p>
 *
 * @author 杨浩泉
 * @since 2019-07-08
 */
@RestController
@RequestMapping("/weixin/menu")
public class WeixinMenuController extends MyBaseController {
	
	@Autowired 
	private WeixinMenuService service;

    /**
	 * 添加
	 * 
	 * @param entity
	 * @param bindingResult
	 * @return
	 */
	@PostMapping("/add")
	public Object add(@Valid @RequestBody WeixinMenu entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return R.warning(bindingResult.getFieldError().getRejectedValue().toString());
		}
		
		if(null != entity.getType()) {
			if(StringUtils.isBlank(entity.getKeyValue())) {
				entity.setKeyValue(entity.getType().toUpperCase() + "_" + RandomUitl.generateString(5).toUpperCase());
			} else {
				entity.setKeyValue(entity.getType().toUpperCase() + "_" + RandomUitl.generateString(5).toUpperCase() + "_" + entity.getKeyValue());
			}
		}
		
		boolean save = this.service.save(entity);
		if (save) {
			return R.ok("提交成功");
		} else {
			return R.failure("提交失败");
		}
	}

	/**
	 * 根据ID删除
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("/deleteById/{id}")
	public Object deleteById(@PathVariable String id) {
		if (StringUtils.isNotBlank(id)) {
			boolean remove = this.service.removeById(id);
			if (remove) {
				return R.ok();
			} else {
				return R.failure("通过ID删除失败：[ " + id + " ]");
			}
		}
		return R.failure("请选项需要删除的记录");
	}

	/**
	 * 根据ID批量删除
	 * 
	 * @param idList ["1","2"]
	 * @return
	 */
	@PostMapping("/deleteBatchIds")
	public Object deleteBatchIds(@RequestBody List<String> idList) {
		if (null != idList && !idList.isEmpty()) {
			boolean remove = this.service.removeByIds(idList);
			if (remove) {
				return R.ok();
			} else {
				return R.failure("通过ID删除失败：[ " + idList + " ]");
			}
		}
		return R.failure("请选项需要删除的记录");
	}

	/**
	 * 修改
	 * 
	 * @param entity
	 * @param bindingResult
	 * @return
	 */
	@PostMapping("/update")
	public Object update(@Valid @RequestBody WeixinMenu entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return R.failure(bindingResult.getFieldError().getDefaultMessage().toString());
		}
		boolean update = this.service.updateById(entity);
		if (update) {
			return R.ok("修改成功");
		} else {
			return R.failure("修改失败");
		}
	}

	/**
	 * 根据ID查询
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("/get/{id}")
	public Object get(@PathVariable Long id) {
		WeixinMenu entity = this.service.getById(id);
		if (null != entity) {
			return R.ok(entity);
		} else {
			return R.failure("通过ID查询失败：[ " + id + " ]");
		}
	}

	/**
	 * 查询所有数据，不分页
	 * 
	 * @param entity
	 * @return
	 */
	@GetMapping(value = "/list")
	public Object list(WeixinMenu entity) {
		return R.ok(this.service.list(new QueryWrapper<WeixinMenu>(entity).orderByDesc("ctime")));
	}

	/**
	 * 分页查询数据
	 * 
	 * @param entity
	 * @return
	 */
	@GetMapping(value = "/page")
	public Object page(WeixinMenu entity) {
		return R.ok(this.service.selectPage(new QueryWrapper<WeixinMenu>(entity).orderByDesc("sort"), new PageBean(request)));
	}

	/**
	 * 树状JSON结构
	 * 
	 * @param entity
	 * @return
	 */
	@GetMapping(value = "/treeGrid")
	public Object treeGrid(WeixinMenu entity) {
		QueryWrapper<WeixinMenu> queryWrapper = new QueryWrapper<WeixinMenu>();
		queryWrapper.eq(entity.getPid() != null, "pid", entity.getPid());
		queryWrapper.orderByDesc("sort");
		List<WeixinMenu> list = this.service.list(queryWrapper) ;
		
		List<WxMenuTreeNode> treeNodes = new ArrayList<WxMenuTreeNode>();
		for (WeixinMenu item : list) {
			WxMenuTreeNode node = new WxMenuTreeNode();
			node.setId(item.getId());
			node.setPid(item.getPid());
			node.setType(item.getType());
			node.setName(item.getName());
			node.setKeyValue(item.getKeyValue());
			node.setUrl(item.getUrl());
			node.setMediaId(item.getMediaId());
			node.setAppid(item.getAppid());
			node.setPagepath(item.getPagepath());
			node.setTemplateId(item.getTemplateId());
			node.setTemplateType(item.getTemplateType());
			node.setParams(item.getParams());
			node.setSort(item.getSort());
			node.setStatus(item.getStatus());
			node.setCtime(item.getCtime());
			node.setUtime(item.getUtime());
			treeNodes.add(node);
		}
		
		return R.ok(new WxMenuTreeGridUtil().tree(treeNodes));
	}
	
	/**
	 * 将菜单推送到微信服务器
	 * @param appid
	 * @return
	 */
	@GetMapping(value = "/pushMenuToServer")
	public Object pushMenuToServer() {
		boolean flag = this.service.pushMenuToServer();
		if(flag) {
			return R.ok();
		} else {
			return R.failure("菜单推送到微信服务器失败");
		}
	}
	
}



